<template>
  <div class="contextmenu" :style="{left: style.left + 'px',top: style.top + 'px', }" @contextmenu.prevent>
    <div :class="{'item_disable':item.disable, 'item_divider':item.divider,'item':!item.divider}"
         v-for="item in menus" :key="item.name" @click="handleClickMenuItem(item)" @mousedown.stop>
      <div class="item_divider_line" v-show="item.divider"></div>
      <div v-show="!item.divider" class="item_title">
        <el-icon>
          <component :is="item.icon" />
        </el-icon>
        {{item.name}}
      </div>
    </div>
  </div>
</template>
<script>

export default {
  name: 'ContextmenuComponent',
  props: {
    axis: Object,
    el: Object,
    menus: Array,
    removeContextmenu: Function
  },
  data () {
    return {

    }
  },
  computed: {
    style () {
      const MENU_WIDTH = 130
      const MENU_HEIGHT = 30
      const DIVIDER_HEIGHT = 10
      const PADDING = 10

      const { x, y } = this.$props.axis
      const menuCount = this.$props.menus.filter(menu => !(menu.divider || menu.hide)).length
      const dividerCount = this.$props.menus.filter(menu => menu.divider).length

      const menuWidth = MENU_WIDTH
      const menuHeight = menuCount * MENU_HEIGHT + dividerCount * DIVIDER_HEIGHT + PADDING * 2

      const screenWidth = document.body.clientWidth
      const screenHeight = document.body.clientHeight

      return {
        left: screenWidth <= x + menuWidth ? x - menuWidth : x,
        top: screenHeight <= y + menuHeight ? y - menuHeight : y
      }
    }
  },
  created () {

  },
  mounted () {

  },
  activated () {

  },
  methods: {
    handleClickMenuItem (item) {
      if (item.disable) return
      if (item.children && !item.handler) return
      if (item.handler) item.handler(item, this.el)
      this.removeContextmenu()
    }
  },
  deactivated () {

  },
  unmounted () {

  },
  components: {}
}
</script>

<style>
.contextmenu-pop{
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 9998;
}
</style>
<style scoped lang='scss'>
.contextmenu {
  position: fixed;
  z-index: 9999;
  user-select: none;
  background-color: white;
  min-width: 130px;
  padding: 10px 0;
  box-shadow: 0 0 6px #bcbcbc;
  border-radius: 4px;
  .item{
    height: 30px;
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 12px;
    padding: 0 10px;
  }
  .item_title{
    display: flex;
    align-items: center;
    height: 100%;
    .el-icon{
      margin-right: 5px;
    }
  }
  .item_divider{
    width: 100%;
    height: 10px;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    padding: 0 5px;
    .item_divider_line{
      width: 100%;
      height: 1px;
      background-color: #e2e2e2;
    }
  }
  .item_disable{
    color: #bcbcbc;
    cursor: not-allowed;
  }
  .item:hover{
    background-color: #E9EDF0;
  }
}
</style>
